package com.mashibing.juc.c_005;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName T04_ReentrantLock4
 * @Description 使用ReentrantLock还可以调用lockInterruptibly方法，可以对线程的interrupt做出响应
 * @Author xiongwei.wu
 * @Date 2021/7/12 10:54
 **/
public class T04_ReentrantLock4 {
    public static void main(String[] args) {
        Lock lock = new ReentrantLock();

        Thread t1 = new Thread(() -> {
            lock.lock();
            System.out.println("t1 start");
            try {
                TimeUnit.SECONDS.sleep(Integer.MIN_VALUE);
            } catch (InterruptedException e) {
                System.out.println("t1 interrupted!!!");
            } finally {
                lock.unlock();
            }
            System.out.println("t1 end");
        });
        t1.start();

        Thread t2 = new Thread(() -> {
//            lock.lock();
            //可以对interrupt方法做出响应
            try {
                lock.lockInterruptibly();
                System.out.println("t2 start");
                TimeUnit.SECONDS.sleep(5);
                System.out.println("t2 end");
            } catch (InterruptedException e) {
                System.out.println("t2 interrupted!!!");
            } finally {
                lock.unlock();
            }
        });
        t2.start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.interrupt();//打断线程2的等待
    }
}
